package com.naszetatry.registration;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.naszetatry.beans.User;
import com.naszetatry.controller.LoginController;
import com.naszetatry.controller.RegistrationController;
import com.naszetatry.exception.InvalidLoginException;
import com.naszetatry.exception.InvalidMailException;
import com.naszetatry.exception.InvalidPasswordException;
import com.naszetatry.logic.UserLogic;
import com.naszetatry.mail.MailSender;
/**
 * Serwlet odpowiedzialny za przypomnienie hasla.
 * Po wypelnieniu formularza, wysyla maila z nowym haslem.
 * @author Maciej Koch
 *
 */
public class PasswordReminder extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		if("1".equals(request.getParameter("do"))) {
			getServletContext().getRequestDispatcher("/jsp/passwordReminder.jsp").forward(request, response);
			return;
		}
		String login = request.getParameter("login");
		String mail = request.getParameter("mail");
		User user = new User();
		user.setLogin(login);
		user.setMail(mail);
		boolean passwordChangedAccepted = true;
			
		User newUser = new User();
		String newPassword = UserLogic.generateNewPassword();
		newUser.setPassword(newPassword);
		newUser.setLogin(user.getLogin());
		try {
			UserLogic.updatePassword(newUser);
		} catch (InvalidPasswordException e) {
			//password is irrelevant
		} catch (InvalidLoginException e) {
			passwordChangedAccepted = false;
		}
				
		if(passwordChangedAccepted) {
			MailSender mailSender = new MailSender();
			boolean hasMailSent = mailSender.send(user.getMail(), "Zmiana hasla", "haslo: " + newPassword);
			//nie udalo sie wyslac maila
			if(!hasMailSent) {
				getServletContext().getRequestDispatcher("/jsp/mailFailed.jsp").forward(request, response);
				return;
			}
			getServletContext().getRequestDispatcher("/jsp/passwordReminderSuccess.jsp").forward(request, response);

		}
		else {
			RValidation validation = new RValidation();
			validation.isLoginValid = false;
			validation.isMailValid = false;
			RegistrationController.setPasswordChangeValidation(request, validation);
			RegistrationController.setRegisteredUser(request, user);
			getServletContext().getRequestDispatcher("/jsp/passwordReminder.jsp").forward(request, response);
		}
		
		
	}
}
